package com.pw.gmall.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.pw.gmall.realtime.app.BaseApp;
import com.pw.gmall.realtime.common.Constant;
import com.pw.gmall.realtime.utils.AtguiguUtils;
import com.pw.gmall.realtime.utils.KafkaUtils;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @Author: linux_future
 * @since: 2022/3/19
 **/
public class DwmUvApp extends BaseApp {
    public static void main(String[] args) {
        new DwmUvApp().init(2003, 1, "dwmUvApp", "dwmUvApp", Constant.TOPIC_DWD_PAGE_LOG);
    }


    @Override
    protected void handler(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        System.out.println("数据流处理。。。。。。。。。。。。。。。。。。。。。。。。。。");
        //logger 构建数据---kafka--dwdLog数据分流--到这里
         stream.print();
        //数据处理

        WatermarkStrategy<JSONObject> wms = WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner(((obj, ts) -> obj.getLong("ts")));
        stream
                .map(JSON::parseObject)
                .assignTimestampsAndWatermarks(wms)
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {

                    private SimpleDateFormat sdf;
                    private ValueState<String> dateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        dateState = getRuntimeContext().getState(
                                new ValueStateDescriptor<String>("dateState", String.class));

                        sdf = new SimpleDateFormat("yyyy-MM-dd");
                    }

                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<JSONObject> elements,
                                        Collector<JSONObject> out) throws Exception {
                        String yesterday = dateState.value();
                        String today = sdf.format(ctx.window().getStart());

                        if (!today.equals(yesterday)) {
                            // 今天和昨天不一样, 跨天
                            dateState.clear();
                        }


                        if (dateState.value() == null) {
                            // 表示第一个窗口
                            // 只有第一个窗口才有必要把Iterable转成List, 其他的窗口, 可以直接忽略
                            List<JSONObject> list = AtguiguUtils.toList(elements);
                        /*Collections.min(list, new Comparator<JSONObject>(){
                            @Override
                            public int compare(JSONObject o1, JSONObject o2) {
                                return o1.getLong("ts").compareTo(o2.getLong("ts"));
                            }
                        });*/
                            //                        Collections.min(list, (o1, o2) -> o1.getLong("ts").compareTo(o2.getLong("ts")));
                            JSONObject min = Collections.min(list, Comparator.comparing(o -> o.getLong("ts")));
                            out.collect(min);

                            // 更新状态  年月日
                            dateState.update(sdf.format(min.getLong("ts")));
                        }


                    }
                })
                .map(JSONAware::toJSONString)
                .addSink(KafkaUtils.getKafkaSink(Constant.TOPIC_DWM_UV));
    }
}
